package com.weiyi.mashangzhu.Roomer.Activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Adapter.CouponAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.Coupon_OrderAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.MessageAdapter;
import com.weiyi.mashangzhu.Roomer.Bean.AllCommentInfo;
import com.weiyi.mashangzhu.Roomer.Bean.CouponBean;
import com.weiyi.mashangzhu.Roomer.Bean.PersonInfoBean;
import com.weiyi.mashangzhu.Roomer.Fragment.Fragment_Message;
import com.weiyi.mashangzhu.Utils.GlideImgManager;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class CouponActivity extends BaseActivity {

    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.vp_view)
    ViewPager mViewPager;
    PullToRefreshListView pullToRefreshListView_in, pullToRefreshListView_out;
    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private List<View> mViewList = new ArrayList<>();//页卡视图集合
    private View view1;
    private View view2;
    int page = 1;
    int page2 = 1;
    CouponAdapter adapter = null;
    CouponAdapter adapter2 = null;
    Coupon_OrderAdapter coupon_orderAdapter;
    Coupon_OrderAdapter coupon_orderAdapter2;
    List<CouponBean.DataBean.WithinTimeCouponsBean> w = new ArrayList<>();
    List<CouponBean.DataBean.OverTimeCouponsBean> o = new ArrayList<>();
    String info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupon);
        ButterKnife.bind(this);
        info = getIntent().getStringExtra("info");
        mInflater = LayoutInflater.from(this);
        view1 = mInflater.inflate(R.layout.fragment_coupon_intime, null);
        view2 = mInflater.inflate(R.layout.fragment_coupon_outtime, null);
        pullToRefreshListView_in = (PullToRefreshListView) view1.findViewById(R.id.refresh_list);
        pullToRefreshListView_out = (PullToRefreshListView) view2.findViewById(R.id.refresh_list);

        //添加页卡视图
        mViewList.add(view1);
        mViewList.add(view2);
        if (info.equals("order")) {
            //添加页卡标题
            mTitleList.add("可使用");
            mTitleList.add("不可使用");
            coupon_orderAdapter = new Coupon_OrderAdapter(MyApp.couponlistBeanList_yes, this, "yes");
            coupon_orderAdapter2 = new Coupon_OrderAdapter(MyApp.couponlistBeanList_no, this, "no");
            pullToRefreshListView_in.setAdapter(coupon_orderAdapter);
            pullToRefreshListView_out.setAdapter(coupon_orderAdapter2);
            pullToRefreshListView_in.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent();
                    intent.putExtra("CPrice", MyApp.couponlistBeanList_yes.get(position - 1).getCPrice());
                    intent.putExtra("CQuota", MyApp.couponlistBeanList_yes.get(position - 1).getCQuota());
                    intent.putExtra("id", MyApp.couponlistBeanList_yes.get(position - 1).getId());
                    setResult(0x002, intent);
                    finish();
                }
            });

        } else {
            //添加页卡标题
            mTitleList.add("可使用");
            mTitleList.add("不可使用");
            initData(1);


            pullToRefreshListView_in.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                        @Override
                        public void onPullDownToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullDownToRefresh");
                            //这里写下拉刷新的任务
                            new DownGetDataTask().execute();
                        }

                        @Override
                        public void onPullUpToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullUpToRefresh");
                            new UpGetDataTask().execute();
                        }
                    });
            pullToRefreshListView_out.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                        @Override
                        public void onPullDownToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullDownToRefresh");
                            //这里写下拉刷新的任务
                            new DownGetDataTask2().execute();
                        }

                        @Override
                        public void onPullUpToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullUpToRefresh");
                            new UpGetDataTask2().execute();
                        }
                    });
        }
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式，当前为系统默认模式
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));


        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器
    }

    private void initData(final int i) {
        Log.e("www", "initData: " + SPUtils.get(this, "token", "") + "" + "==" + i);
        OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "")
                .addParams("pagenum", i + "")
                .url(API.BaseApi_R + API.Coupon_Api)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        T.showShort(CouponActivity.this, "网络连接失败，请检查一下网络设置");
                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("status") == 1) {
                                T.showShort(CouponActivity.this, jsonObject.getString("msg"));
//                                SPUtils.put(CouponActivity.this, "isLogin", "0");
                            } else {
                                CouponBean couponbean = new Gson().fromJson(response, CouponBean.class);
                                if (i == 1) {
                                    w.clear();
                                    o.clear();
                                    w = couponbean.getData().getWithinTimeCoupons();
                                    o = couponbean.getData().getOverTimeCoupons();
                                    adapter = new CouponAdapter(null, w, CouponActivity.this, "w");
                                    adapter2 = new CouponAdapter(o, null, CouponActivity.this, "o");
                                    pullToRefreshListView_in.setAdapter(adapter);
                                    pullToRefreshListView_out.setAdapter(adapter2);
                                } else {
                                    w.addAll(couponbean.getData().getWithinTimeCoupons());
                                    o.addAll(couponbean.getData().getOverTimeCoupons());
                                    adapter.notifyDataSetChanged();
                                    adapter2.notifyDataSetChanged();
                                }

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    private class DownGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page = 1;
            initData(page2);

            pullToRefreshListView_in.onRefreshComplete();
        }
    }

    private class UpGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page += 1;
            initData(page2);
            pullToRefreshListView_in.onRefreshComplete();
        }
    }


    private class DownGetDataTask2 extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page2 = 1;
            initData(page2);
            pullToRefreshListView_out.onRefreshComplete();
        }
    }

    private class UpGetDataTask2 extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page2 += 1;
            initData(page2);
            pullToRefreshListView_out.onRefreshComplete();
        }
    }


    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }

    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);//页卡标题
        }

    }
}
